package com.zxc.reggie.controller;

import com.zxc.reggie.Utils.ValidateCodeUtils;
import com.zxc.reggie.common.R;
import com.zxc.reggie.entity.User;
import com.zxc.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody Map<String, String> map) {
        String phone = map.get("phone");

        if (StringUtils.isNotEmpty(phone)) {
            String code4String = ValidateCodeUtils.generateValidateCode4String(4);
            session.setAttribute(phone, code4String);
            log.info("验证码:" + code4String);
            return R.success("获取验证码成功");
        }
        return R.error("获取验证码失败");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> map,HttpSession session) {
        String code = map.get("code");
        String phone = map.get("phone");

        if(code==null||phone==null){
            return R.error("登录失败");
        }
        String SessionCode = (String) session.getAttribute(phone);
        if(SessionCode==null){
            return R.error("登录失败");
        }

        if(!code.equals(SessionCode)){
            return R.error("验证码有误");
        }
        User user = userService.query().eq("phone", phone).one();
        if(user==null){
            user = new User();
            user.setStatus(1);
            user.setPhone(phone);
            userService.save(user);
        }
        log.info("user:"+user.getId());
        session.setAttribute("user",user.getId());
        return R.success("登录成功");
    }
}
